package com.story.api.moduler.song.interceptor;

import com.story.api.config.properties.JwtProperties;
import com.story.api.moduler.song.service.PlayRecordService;
import com.story.api.moduler.user.util.JwtTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 浏览记录统计拦截器
 * @author yangbo
 * @date 2019-09-23 16:55
 */
public class PlayRecordInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PlayRecordService playRecordService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // 看用户是否登录，未登录的直接放过;已登录的
        Integer userId = getUserId(httpServletRequest);
        if(userId != null) {
            //将用户信息与观看记录做
            String playPath = httpServletRequest.getParameter("playPath");
            String[] playPathArr = playPath.split("/");
            StringBuilder sb = new StringBuilder();
            for (int i = playPathArr.length - 3; i < playPathArr.length; i++) {
                sb.append("/").append(playPathArr[i]);
            }
            String filePath = sb.toString();
            playRecordService.playRecord(userId,filePath);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {


    }

    /**
     * 通过jwt得到userId
     * @return
     */
    private Integer getUserId(HttpServletRequest request) {
        final String requestHeader = request.getHeader(jwtProperties.getHeader());
        String authToken = null;
        if (StringUtils.isNotBlank(requestHeader) && requestHeader.startsWith("Bearer ")) {
            authToken = requestHeader.substring(7);
            Integer userId = Integer.valueOf(jwtTokenUtil.getUsernameFromToken(authToken));
            return userId;
        } else {
            return null;
        }
    }
}
